package com.kaili.basic.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.*;
import com.kaili.basic.pojo.entity.MdmPushGroupEntity;
import com.kaili.basic.pojo.vo.MdmPushGroupByNameVo;
import com.kaili.basic.pojo.vo.MdmPushGroupQueryAllVo;
import com.kaili.basic.pojo.vo.MdmPushGroupVO;
import com.kaili.basic.service.IMdmOrgService;
import com.kaili.basic.service.IMdmPushGroupService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.exception.RestException;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @Desc: 推送组的管理
 * @author: TBS
 * @Time: 2019/8/1 18:57
 * @Copyright: © 2018 杭州凯立通信有限公司 版权所有
 * @Warning: 本内容仅限于公司内部传阅,禁止外泄或用于其它商业目的
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@Api(tags = "推送组管理",description = "推送组相关API")
@RestController
public class MdmPushGroupController {

//    Logger LOGGER = LoggerFactory.getLogger(MdmPushGroupController.class);
    private static Logger log = LoggerFactory.getLogger(MdmPushGroupController.class);

    public volatile String pushGroupCode;
    @Autowired
    private IMdmPushGroupService mdmPushGroupService;
    @Autowired
    private IMdmOrgService mdmOrgService;

    /**
     * @param mdmRangeQueryDto
     * @return java.util.List
     * @Desc: 条件查询机构或者分组
     * @author: TBS
     * @Time: 2019/8/1 18:58
     */
    @GetMapping(value = "pushgroup/searchRanges")
    @ApiOperation(value = "条件查询机构或者分组", notes = "条件都是不必填")
    public List searchRanges(@ModelAttribute MdmRangeQueryDto mdmRangeQueryDto) {
        mdmRangeQueryDto.setEmployeeId(LoginDetailUtils.getCurrentEmployeeId().longValue());
        if (mdmRangeQueryDto.getStatus() != null && mdmRangeQueryDto.getStatus() == 1) {
            MdmOrgQueryDto mdmOrgQueryDto = new MdmOrgQueryDto();
            mdmOrgQueryDto.setOrgName(mdmRangeQueryDto.getSearch());
            return mdmPushGroupService.queryOrgRanges(mdmOrgQueryDto);
        } else {
            MdmGroupQueryDto mdmGroupQueryDto = new MdmGroupQueryDto();
            mdmGroupQueryDto.setGroupName(mdmRangeQueryDto.getSearch());
            return TreeParserUtil.getTreeList("0", mdmPushGroupService.queryGroupRanges(mdmGroupQueryDto));
        }
    }

    /**
     * @param mdmPushGroupAddDto
     * @return com.kaili.common.response.RestStatus
     * @Desc: 推送组增加
     * @author: TBS
     * @Time: 2019/8/1 18:59
     */
    @PostMapping(value = "/pushgroup/addPushGroup")
    @ApiOperation(value = "新增mdm推送组", notes = "新增mdm推送组")
    public RestStatus addPushGroup(@Validated @RequestBody MdmPushGroupAddDto mdmPushGroupAddDto) {
        MdmPushGroupEntity mdmPushGroupEntity1 = new MdmPushGroupEntity();
        mdmPushGroupEntity1.setPushGroupName(mdmPushGroupAddDto.getPushGroupName());
        mdmPushGroupEntity1.setPushGroupCode(mdmPushGroupAddDto.getPushGroupCode());

        Integer count = mdmPushGroupService.querySupplierPushGroup(mdmPushGroupEntity1);
        if (count > 0) {
            return CommonStatus.RENT_REPETITION;
        }
        mdmPushGroupAddDto.setCreateBy(LoginDetailUtils.getCurrent().getId());
        mdmPushGroupAddDto.setCreateTime(new Date());

        MdmPushGroupEntity mdmPushGroupEntity = ObjectUtils.toObject(mdmPushGroupAddDto, MdmPushGroupEntity.class);
        if(mdmPushGroupAddDto.getGroupRange()!=null && !mdmPushGroupAddDto.getGroupRange().isEmpty()) {

            mdmPushGroupService.addPushGroup(mdmPushGroupEntity);
            return CommonStatus.ADD_OK;
        }
            return CommonStatus.ADD_FAIL;
    }


    /***
     * @Desc: 推送组删除
     * @author: TBS
     * @Time: 2019/8/5 10:14
     * @param
     * * @return com.kaili.common.response.RestStatus
     */
    @ApiOperation(value = "推送组删除")
    @DeleteMapping("/pushgroup/{id}")
    public RestStatus deletePushGroup(@PathVariable("id") int id) {
        mdmPushGroupService.delete(id);
        return CommonStatus.DELETE_OK;
    }


    /***
     * @Desc: 推送组 code自增
     * @author: TBS
     * @Time: 2019/8/2 15:27
     * @param
     * @return
     */
    @ApiOperation(value = "新增推送组时获取推送组编码")
    @GetMapping("/pushgroup/code")
    public String getPushGroupCode() {
        if (!StringUtils.isEmpty(pushGroupCode)) {
            pushGroupCode = addValue(pushGroupCode);
            return pushGroupCode;
        }
        String code = mdmPushGroupService.getCode();
        String pushGroupCode = addValue(code);
        return pushGroupCode;
    }

    public static String addValue(String str) {
        Integer str1 = Integer.parseInt(str);
        String str2 = str1.toString();
        int index = str.length() - str2.length() - 1;

        int temp = 0;
        //以0开头的
        if (str.startsWith("0") && index != -1) {
            temp = index + 1;
        }
        Integer integer = null;
        try {
            integer = Integer.valueOf(str);
        } catch (NumberFormatException e) {
//            LOGGER.info("输入的字符串不是纯数字字符串...");
            log.error("用户管理导出异常"+e.getMessage());
        }
        integer++;
        String newNum = integer.toString();

        if (newNum.length() > str.length() - temp) {
            temp--;
        }
        StringBuffer sb = new StringBuffer();
        if (temp != 0) {
            for (int i = 0; i < temp; i++) {
                sb.append("0");
            }
        }
        sb.append(newNum);
        return sb.toString();
    }

    @ApiOperation(value = "修改推送组")
    @PutMapping("/pushgroup")
    public RestStatus updatePushGroup(@RequestBody MdmPushGroupUpdateDto mdmPushGroupUpdateDto) {
        mdmPushGroupUpdateDto.setModifyBy(LoginDetailUtils.getCurrent().getId());
        mdmPushGroupUpdateDto.setModifyTime(new Date());
        MdmPushGroupEntity mdmPushGroupEntity = ObjectUtils.toObject(mdmPushGroupUpdateDto, MdmPushGroupEntity.class);
        if (mdmPushGroupUpdateDto.getGroupRange() != null && !mdmPushGroupUpdateDto.getGroupRange().isEmpty()) {
            mdmPushGroupService.update(mdmPushGroupEntity);
            return CommonStatus.UPDATE_OK;
        }
            return CommonStatus.UPDATE_FAIL;

    }

    @ApiOperation(value = "推送组导入")
    @PostMapping("/pushgroup/import")
    public void export(MultipartFile file) throws RestException {
        List<MdmPushGroupQueryAllVo> list = ExcelUtil.importExcel(file, 1, 1, MdmPushGroupQueryAllVo.class);
        MdmPushGroupEntity mdmPushGroupEntity;
        for (MdmPushGroupQueryAllVo mdmPushGroupQueryAllVo : list) {
            mdmPushGroupQueryAllVo.setCreateBy(LoginDetailUtils.getCurrent().getId());
            mdmPushGroupQueryAllVo.setCreateTime(new Date());
            mdmPushGroupEntity = ObjectUtils.toObject(mdmPushGroupQueryAllVo, MdmPushGroupEntity.class);
            mdmPushGroupService.addPushGroup(mdmPushGroupEntity);
        }
    }

    /**
    * @Desc:  分页查询推送组信息
    * @author: TBS
    * @Time: 2019/8/6 10:39
    * @param mdmPushGroupQueryDto
    * @return com.baomidou.mybatisplus.plugins.Page<com.kaili.basic.pojo.vo.MdmPushGroupVO>
    */
    @GetMapping(value = "/pushgroup/pageList")
    @ApiOperation(value = "分页查询推送组信息", notes = "分页查询推送组信息")
    public Page<MdmPushGroupVO> queryMdmMessages(@ModelAttribute MdmPushGroupQueryDto mdmPushGroupQueryDto) {
        return mdmPushGroupService.queryPushGroup(new Page<MdmPushGroupVO>(mdmPushGroupQueryDto.getPage(), mdmPushGroupQueryDto.getPageSize()), mdmPushGroupQueryDto);
    }

    /**
    * @Desc:  推送组导出
    * @author: TBS
    * @Time: 2019/8/6 10:39
    * @param response
    * @param mdmPushGroupQueryDto
    * @return void
    */
    @GetMapping("/pushgroup/export")
    @ApiOperation(value = "推送组导出",notes = "推送组导出")
    public void export(HttpServletResponse response,@ModelAttribute MdmPushGroupQueryDto mdmPushGroupQueryDto) throws RestException {
        List<MdmPushGroupVO> list=mdmPushGroupService.export(mdmPushGroupQueryDto);
        ExcelUtil.exportExcel(list,"推送组管理","sheet1", MdmPushGroupVO.class, UUID.randomUUID().toString()+".xls",response);
    }

    /**
    * @Desc: 根据名称查询id和名称
    * @author: TBS
    * @Time: 2019/8/6 10:39
    * @param mdmPushGroupByNameDto
    * @return java.util.List<com.kaili.basic.pojo.vo.MdmPushGroupByNameVo>
    */
    @GetMapping("/pushgroup/queryByName")
    @ApiOperation(value = "根据名称查询id和名称",notes = "根据名称查询id和名称")
    public List<MdmPushGroupByNameVo> queryByName(@ModelAttribute MdmPushGroupByNameDto mdmPushGroupByNameDto){
        return mdmPushGroupService.queryByName(mdmPushGroupByNameDto);
    }

    /**
    * @Desc: 根据ID查询详情
    * @author: TBS
    * @Time: 2019/8/6 16:28
    * @param id
    * @return com.kaili.basic.pojo.vo.MdmPushGroupVO
    */
    @GetMapping("/pushgroup/ById/{id}")
    @ApiOperation(value = "根据id查询详情信息",notes = "根据id查询详情信息")
    public MdmPushGroupVO queryById(@PathVariable("id") Integer id){


        return mdmPushGroupService.queryById(id);
    }
}